library(tidyverse)
library(tidylog)
library(readr)
library(reshape2)
library(xtable)
library(pdftools)
library(magick)
library(gridExtra)
library(grid)
library(cowplot)

fff_events <- read_csv("data/output/fff_events.csv")
fff_orgs <- fff_events %>%
  select(org) %>%
  group_by(org) %>%
  count() %>%
  distinct()

fff_urls <- fff_events %>%
  select( url) %>%
  distinct()

fff_urls$url_formatted <- eval(parse(text=gsub("\\", "", deparse(fff_urls$url), fixed=TRUE)))

fff_urls$url_formatted <- gsub("<a href='", "", fff_urls$url_formatted)

fff_urls$url_formatted <- sub("\\'.*", "", fff_urls$url_formatted)

fff_urls <- fff_urls %>%
  filter(!is.na(url))

write_csv(fff_urls, "data/output/fff_urls_formatted.csv")

# *code in Google Sheets*
fff_events <- read_csv("data/output/fff_urls_formatted_coded.csv")

fff_orgs <- fff_events %>%
  select(organization1, organization2, organization3, organization4, organization5, organization6, organization7, organization8) %>%
  mutate(id = seq(1:nrow(fff_events)))


fff_orgsm <- melt(fff_orgs,id.vars=c("id"))
orgs <- fff_orgsm$value

orgs <- gsub(".*XR.*", "XR", orgs)
orgs <- gsub(".*Fridays for Future.*", "FFF", orgs)
orgs <- gsub(".*Student Climate.*", "Student Climate Network", orgs)
orgs <- gsub("Youth Strike for Climate", "Youth Strike 4 Climate", orgs)


orgs <- as.data.frame(orgs[!is.na(orgs)])
colnames(orgs) <- "orgname"

orgcounts <- orgs %>%
  group_by(orgname) %>% 
  count() %>%
  arrange(desc(n))

saveRDS(orgcounts, "data/output/orgcounts.rds")

x.big <- xtable(orgcounts, digits = 0)
print(x.big,  tabular.environment = "longtable", floating = F, include.rownames=FALSE)


## gen facebook image plot

imgfiles <- list.files("data/images/")
imgfiles <- paste0("data/images/", imgfiles)

imglist <- list()

for (i in seq_along(imgfiles)) {
  
  imgfile <- imgfiles[[i]]
  
  img <- image_read(imgfile)
  img <- image_convert(img)
  grob_img <- rasterGrob(img)
  
  imglist[[i]] <- grob_img
  
}

png("plots/figa6.png", 
    width = 400, height = 300, units='mm', res = 200)
plot_grid(imglist[[1]], imglist[[2]], 
          imglist[[3]], 
          imglist[[4]],
          imglist[[4]], 
          imglist[[5]], imglist[[7]], 
          imglist[[8]],labels = "AUTO", ncol = 4)
dev.off()